var express = require('express');
var router = express.Router();

var nodemailer = require("nodemailer");
var smtpTransport = require('nodemailer-smtp-transport');
var settingConfig = {
    smtp : 'smtp.163.com',
    mailFrom : 'email17813210692@163.com',
    mailPwd : 'BUTNFZOVEBGABMHY',
    secret : '2laoban2laoban0'
};//require('../config/settingConfig.js');//解析参数

var smtp = settingConfig["smtp"];
//var mailFrom = Buffer.from(settingConfig["mailFrom"]).toString('base64');
//var mailPwd = Buffer.from(settingConfig["mailPwd"]).toString('base64');
var mailFrom = settingConfig["mailFrom"];
var mailPwd = settingConfig["mailPwd"];
 
function emailTo(email,subject,text,html,callback) {
// 开启一个 SMTP 连接池
    var transporter = nodemailer.createTransport(smtpTransport({
        host: smtp,//主机
        secure: true, // 使用 SSL
        secureConnection: true, // 使用 SSL
        port: 465, // SMTP 端口
        auth: {
            type:'login',
            user: mailFrom,
            pass: mailPwd //授权码,通过QQ获取  

        }
    }));
    var mailOptions = {
        from: mailFrom, // 发送者  
        to: email, // 接受者,可以同时发送多个,以逗号隔开  
        subject: subject, // 标题  
    };    
    mailOptions.text =text;// 文本  30 
    var result = {
        httpCode: 200,
        message: '发送成功!',
        data: [],
    }
    try {
        transporter.sendMail(mailOptions, function (err, info) {
            if (err) {
                result.httpCode = 500;
                result.message = err;
                callback(result);
                return;
            }
            callback(result);
        });
        //transport || transport.close(); // 如果没用，关闭连接池
    } catch (err) {
        result.httpCode = 500;
        result.message = err;
        callback(result);
    }
    
}

/* GET users listing. */
router.get('/', function(req, res, next) {

    //通过username查询数据库得到email地址
    //产生4位随机数字保存在session
    
  emailTo("1176405461@qq.com","验证码","world!","",function(data){
    res.status(data.httpCode).json(data);
    res.send('Send email success!');
  })
  //res.send('respond with a resource');
});

module.exports = router;
